<template>
  <!-- 购物车 -->
  <div class="cart" style="padding-bottom: 110px">
    <van-nav-bar title="购物车" left-text="返回" :right-text="editing?'完成':'编辑'" left-arrow @click-right="editing=!editing" />
  
    <!-- 购物车为空时显示 -->
    <van-empty description="购物车没有东西了, 请添加" v-if="!this.list.length" />
  
    <!-- 列表 -->
    <van-checkbox-group v-model="idList">
      <ul class="list">
        <li class="flx-cent" v-for="(item,index) in list" :key="item.cartId">
          <van-checkbox @click="selectOne" :name="item.cartId" checked-color="#C03131" icon-size="15px">
          </van-checkbox>
          <div class="fg1 flex">
            <div class="cart-goods">
              <img :src="item.imgUrl" alt />
            </div>
            <div class="cart-container flex2 jc-sb h100pc">
              <p class="goods-msg">{{ item.masterName }}</p>
              <div class="flex jc-sb aic" style="height: 28px">
                <span class="price base">￥{{(item.price/100).toFixed(2)}} </span>
                <!-- 步进器 -->
                <van-stepper :name="index" v-show="editing" :value="item.buyNum" async-change
                  @plus="()=>{updateNum(item,item.buyNum+1)}" @minus="()=>{updateNum(item,item.buyNum-1)}" />
                <!-- 非编辑状态 -->
                <span v-show="!editing" class="f999 f12">x {{item.buyNum}} </span>
              </div>
            </div>
          </div>
        </li>
      </ul>
    </van-checkbox-group>
  
    <!-- 底部 -->
    <van-submit-bar :price="totalMoney" :button-text="editing?'删除':'结算'" @submit="onSubmit">
      <van-checkbox :value="all" icon-size="15px" @click="selectAll">全选 {{ all }}</van-checkbox>
    </van-submit-bar>
    <Footer></Footer>
  </div>
</template>

<script>
import Footer from "../components/Footer.vue";
import request from '../../utils/request';
export default {
  components: {
    Footer,
  },
  data() {
    return {
      all: false, // 是否全选
      idList: [], // cartId的数组
      list: [], // 购物车列表
      editing: false, // 是否正在编辑
    }
  },
  created() {
    this.getList();
  },

  computed: {
    totalMoney() {
      // 根据idLis找到相应的成员
      let selectList = this.list.filter(item => this.idList.includes(item.cartId));
      let money = 0;
      selectList.forEach(item => {
        // 单个商品的总价
        let price = item.price * item.buyNum;
        money += price;
      })
      return money;
    }
  },

  methods: {
    // 选中一个
    selectOne() {
      // 全选
      if (this.idList.length === this.list.length) {
        this.all = true;
      } else {
        this.all = false;
      }
    },


    // 全选
    selectAll() {
      // checked为true时全选
      this.all = !this.all;
      if (this.all) {
        // 把this.list里多有cartId放入this.idList
        this.idList = this.list.map(item => item.cartId);
      } else {
        this.idList = [];
      }
    },

    // 修改购物车数量 buyNum最新的值
    updateNum(item, buyNum) {
      let data = {
        cartId: item.cartId,
        buyNum: buyNum
      }
      request.get('/cart/updateNum', { params: data }).then(res => {
        item.buyNum = buyNum;
      }).catch(() => {
        console.log('更新失败');
      })
    },

    async getList() { 
      let res = await request.get('/cart/list');  

      this.list = res.list.map(item => {
        return {
          ...item,
          isSelect: false
        }
      });
    },

    // 结算或删除
    async onSubmit() {
      if (this.editing) {
        let url = '/cart/del';
        let data = {
          cartId: this.idList
        };
        let res = await request.post(url, data);
        // 留下没选中的商品
        this.list = this.list.filter(item => !this.idList.includes(item.cartId));

      } else {
        if (!this.idList.length) {
          this.$dialog.alert({
            title: '温馨提示',
            message: '请先选择商品',
          });
        } else {
          // 发请求去创建预订单
          let data = {
            totalMoney: this.totalMoney,
            cartId: this.idList
          }
          request.post('/preOrder/create', data).then(res => {
            this.$router.push({
              path: '/order/submit',
              query: {
                preOrderId: res.result.preOrderId
              }
            })
          })

        }
      }
    }
  }

};
</script>

<style lang="less">
@import "./index.less";

.cart {
  .van-submit-bar {
    bottom: 50px;
  }

  .empty {
    margin-top: 150px;

    img {
      width: 80px;
      height: 80px;
    }
  }
}
</style>